package demo07

/**
 * @author xiaoZhao
 * @date 2022/7/25
 * @describe 模式匹配 基础语法
 */
object Test01_PatternMatchBase {
  def main(args: Array[String]): Unit = {
    // 1. 基本的语法
    val x: Int = 2
    val y: String = x match {
      case 1 => "one"
      case 2 => "two"
      case 3 => "three"
      case _ => "other"
    }
    println(y)

    // 2.示例:使用模式匹配实现简单的二元运算
    val a = 25
    val b = 21

    def matchOualop(op: Char) = op match {
      case '+' => a + b
      case '-' => a - b
      case '*' => a * b
      case '/' => a / b
      case _ => "非法运算"
    }

    println(matchOualop('+'))
    println(matchOualop('-'))
    println(matchOualop('\\'))

    // 3.模式守卫
    // 求一个整数的绝对值
    def abs(num: Int) = num match {
      case i if i >= 0 => i
      case i if i < 0 => -i
    }

    println(abs(11))
    println(abs(-11))


  }
}
